package com.swjd.bean;

import java.io.*;
import java.sql.*;

public class sqlBean {
	public Connection conn = null;

	public ResultSet rs = null;
	
	private String password="123456";

	private String DatabaseDriver = "com.mysql.jdbc.Driver";
	// DataSource 数据源名称DSN
	private String DatabaseConnStr = "jdbc:mysql://localhost:3306/train?useUnicode=true&characterEncoding=utf-8"
			+ ",root,wenwenwen";

	// 定义方法
	public void setDatabaseDriver(String Driver) {
		this.DatabaseDriver = Driver;
	}

	public String getDatabaseDriver() {
		return (this.DatabaseDriver);
	}

	public void setDatabaseConnStr(String ConnStr) {
		this.DatabaseConnStr = ConnStr;
	}

	public String getDatabaseConnStr() {
		return (this.DatabaseConnStr);
	}

	public sqlBean() {
		try {

			Class.forName(DatabaseDriver);
		} catch (ClassNotFoundException e) {
			System.err.println("加载驱动器有错误:" + e.getMessage());
			System.out.print("执行插入有错误:" + e.getMessage());// 输出到客户端
		}
	}

	public int executeInsert(String sql) {
		int num = 0;
		try {
			conn = DriverManager
					.getConnection(
							"jdbc:mysql://localhost:3306/train?useUnicode=true&characterEncoding=utf-8",
							"root", password);
			Statement stmt = conn.createStatement();
			num = stmt.executeUpdate(sql);
		} catch (SQLException ex) {
			System.err.println("执行插入有错误:" + ex.getMessage());
			System.out.print("执行插入有错误:" + ex.getMessage());// 输出到客户端
		}

		CloseDataBase();
		return num;
	}

	// display data

	public ResultSet executeQuery(String sql) {
		rs = null;
		try {
			conn = DriverManager
					.getConnection(
							"jdbc:mysql://localhost:3306/train?useUnicode=true&characterEncoding=utf-8",
							"root", password);
			Statement stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (SQLException ex) {
			System.err.println("执行查询有错误:" + ex.getMessage());
			System.out.print("执行查询有错误:" + ex.getMessage()); // 输出到客户端
		}

		return rs;
	}

	// delete data
	public int executeDelete(String sql) {
		int num = 0;
		try {

			conn = DriverManager
					.getConnection(
							"jdbc:mysql://localhost:3306/train?useUnicode=true&characterEncoding=utf-8",
							"root", password);
			Statement stmt = conn.createStatement();
			num = stmt.executeUpdate(sql);
		} catch (SQLException ex) {
			System.err.println("执行删除有错误:" + ex.getMessage());
			System.out.print("执行删除有错误:" + ex.getMessage()); // 输出到客户端
		}
		CloseDataBase();
		return num;
	}

	// ////////////////
	public void CloseDataBase() {
		try {
			conn.close();
		} catch (Exception end) {
			System.err.println("执行关闭Connection对象有错误：" + end.getMessage());
			System.out.print("执行执行关闭Connection对象有错误：" + end.getMessage()); // 输出到客户端
		}
	}

}
